@tool
extends IUIComponent


class_name InventorySlot


## 道具Item将要变更时的通知
signal event_item_will_changed(slot: InventorySlot, item: InventoryItem)


## 放置的道具
@export var inventory_item: InventoryItem = null: set = set_item


func set_item(value: InventoryItem) -> void:
    if Engine.is_editor_hint():
        inventory_item = value
        return
    if inventory_item:
        inventory_item.event_amount_changed.disconnect(on_amount_changed)
    event_item_will_changed.emit(self, value)
    inventory_item = value
    if inventory_item:
        inventory_item.event_amount_changed.connect(on_amount_changed)

func on_amount_changed(item: InventoryItem) -> void:
    pass

# 返回是否是相同类型的道具
func is_equal(item: InventoryItem) -> bool:
    return inventory_item.source == item.source

# 返回是否有道具放置
func is_empty() -> bool:
    return inventory_item == null

# 非空槽位返回是否有指定大小的容量
func is_space(count: int) -> bool:
    var max_count: int = inventory_item.source.max_stack_count
    return max_count < 1 or (inventory_item.amount + count) <= max_count

# 非空槽位中合并同类道具,返回合并后剩余的量
func merge(item: InventoryItem) -> InventoryItem:
    # 合并容量
    if is_space(item.amount):
        inventory_item.amount += item.amount
        return null
    var left_amount: int = inventory_item.source.max_stack_count - inventory_item.amount
    inventory_item.amount = inventory_item.source.max_stack_count
    item.amount -= left_amount
    return item

# 在空的槽位上放置道具,返回是否全部放置
func place(item: InventoryItem) -> bool:
    var max_count: int = item.source.max_stack_count
    # 按照最大堆叠数量分批放置到后续的Slot中
    if max_count > 0 and item.amount > max_count:
        set_item(item.clip(max_count))
        return false
    set_item(item)
    return true
